<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="结算清单"
                    name="contractList"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                >
                </el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="formData"
                                :label-width="formLabelWidth"
                                :rules="rulesBase"
                                ref="rulesBase"
                                class="demo-ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算编号：">
                                            <span>{{
                                                formData.billNo
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="期数：">
                                            <span>{{ formData.period }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="合同名称：" prop="contractId">
                                           <el-input
                                                v-model="formData.contractName"
                                                autocomplete="off"
                                                readonly
                                            >
                                                <i
                                                    class="
                                                        el-icon-document-copy
                                                    "
                                                    slot="suffix"
                                                     @click="selectContract"
                                                >
                                                </i>
                                            </el-input>
                                            <el-button class="btn-blue" style="margin-left:5px" @click="showContract">查看</el-button>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="外包方：">
                                            <span>{{ formData.outsourcerName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="结算日期：" prop="settlementDate">
                                            <el-date-picker
                                                type="date"
                                                value-format="yyyy-MM-dd"
                                                placeholder="选择日期"
                                                v-model="formData.settlementDate
                                                "
                                                style="width: 100%"
                                            ></el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="币种：">
                                            <span>{{ formData.currency }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="返还保证金（元）：">
                                            <span>{{
                                                formData.amount
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{ state.find(x=>x.value === parseInt(formData.state))?state.find(x=>x.value === parseInt(formData.state)).label:''}}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <!-- v-if="formData.currencyName !== '人民币'" -->
                                    <el-col :span="12" >
                                        <el-form-item label="人民币汇率：">
                                            <span>{{
                                                formData.rmbRate
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="传输财务共享：">
                                            <span>{{ formData.easId ? "已传" : '未传' }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="本位币：">
                                            <span>{{
                                                formData.baseCurName
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                            <el-form-item label="本位币汇率：" prop="baseCurRate">
                                                <el-input
                                                    v-model="formData.baseCurRate"

                                                    v-enter-float2="{
                                                        set: this,
                                                        val:'formData',
                                                        key: 'baseCurRate'
                                                    }"
                                                    placeholder="请输入内容"
                                                    :disabled="!showBaseCurName">
                                                </el-input>
                                            </el-form-item>
                                        </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="录入机构：">
                                            <span>{{
                                                formData.orgName
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="录入日期：">
                                            <span>{{ formData.gmtCreate }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <el-input type="textarea" v-model="formData.remarks" autocomplete="off"></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 结算清单 审核可以修改-->
                    <div id="contractListCon" class="con">
                        <div class="tabs-title" id="contractList">结算清单</div>
                        <div class="e-table">
                            <div class="errorMsg" v-if="errorContractMsg.length>0">
                                <span>
                                    {{ errorContractMsg.join(',') }}
                                </span>
                            </div>
                            <el-table
                                :data="settlementList"
                                ref="settlementListTable"
                                border
                                style="width: 100%; margin-bottom: 20px"
                                :row-class-name="tableRowClassName"
                                class="table"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{'tableData': settlementList, '_this': this, 'ref': 'settlementListTable'}"
                            >
                                <el-table-column
                                    prop="itemNo"
                                    label="细目编号"
                                    width="100"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.itemNo }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="itemName"
                                    label="细目名称"
                                    min-width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.itemName }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="contractProportion"
                                    label="合同比例"
                                    width="100"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.contractProportion + '%' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="contractAmount"
                                    label="合同金额"
                                    width="100"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.contractAmount }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="previousTotalProportion"
                                    label="截止上期末累计结算比例"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.previousTotalProportion + '%' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="previousTotalAmount"
                                    label="截止上期末累计结算金额"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.previousTotalAmount }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="settlementProportion"
                                    label="本期结算比例"
                                    width="150"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.settlementProportion + '%' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="settlementAmount"
                                    label="本期结算金额"
                                    width="150"
                                >
                                    <template slot-scope="{ row,$index }">
                                        <!-- <el-form :model="row" :rules="settleRules"  :ref="'settlementRef' + $index + 'settlementAmount'" v-if="row.marginType === 2">
                                            <el-form-item prop="settlementAmount">
                                                <el-input v-model="row.settlementAmount"  v-enterAllInteger1 @change="changeAmount(row,$index)"></el-input>
                                            </el-form-item>
                                        </el-form> -->
                                        <el-input v-model="row.settlementAmount"  v-enterAllInteger1 @change="changeAmount(row,$index)" v-if="row.marginType === 2"></el-input>
                                        <span v-else>--</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="currentTotalProportion"
                                    label="截止本期末累计结算比例"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.currentTotalProportion + '%' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="currentTotalAmount"
                                    label="截止本期末累计结算金额"
                                    width="200"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.currentTotalAmount }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                   <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="subcontract"
                        />
                    </div>

                     <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <ExaHistory :billType="1096" :tableData="historyData" @getAuditHistory='getHistoryData'></ExaHistory>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <ComExaButtons :auditState="auditState" :state="formData.state" @exas="exas" :founderId="formData.founderId" />
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>

    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapState, mapMutations } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
import $ from 'jquery'
import { showLoading, hideLoading, throttle, selectDataClient, openAppClient } from '@/utils/common'
import ExaHistory from '@/components/common/exaHistory.vue'
import {  getBond, getBondList, updateBond, updateBondList, listPreviousTotalReturnDepositInfo, deleteBond } from '@/api/settlementManagement/gongchengjieshuan/baozhengjin.js'
import { getAuditHistoryLs, flowCommit, getCurrentState, flowAudit, flowUndoAudit, flownullify  } from '@/api/settlementManagement/gongchengjieshuan/jiakoukuan.js'
import { baseCurRate, isNumInput } from '@/utils/rules.js'
export default {
    data () {
        return {
            //基本信息表单数据
            formData: {
                'amount': 0,
                'baseCurAmount': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'contractId': '',
                'contractName': '',
                'currency': '',
                'currencyId': '',
                'easId': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'outsourcerId': '',
                'outsourcerName': '',
                'period': 0,
                'remarks': '',
                'rmbAmount': 0,
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'settlementDate': '',
                'state': '',
                'workId': ''
            },
            formLabelWidth: '195px',
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
 	        winEvent: {},
            errorList: [], //控制导航栏感叹号的显示
            billid: this.$route.query.billid,
            rulesBase: {
                settlementDate: [
                    { required: true, message: '请选择结算日期', trigger: 'change' },
                ],
                contractId: [
                    { required: true, message: '请选择合同', trigger: 'change' },
                ],
                baseCurRate: [
                    { required: true, validator: baseCurRate, trigger: 'change' },
                ],
            },
            disabled: false, //是否禁止
            auditState: {}, //流程按钮显示状态
            auditParams: {
                'billId': this.$route.query.billid,
                'billType': 1096
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1096,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: ''
            },
            errorServiceMsg: [],
            showBaseCurName: false,
            historyData: [], //审核历史数据
            settlementList: [], //结算列表
            errorBondMsg: [], //清单错误信息
            tableIndex: 0,
            errorContractMsg: [],
            settleRules: {
                settlementAmount: [
                    {
                        required: false,
                        validator: (rule, value, callback)=>{
                            const row = this.settlementList[this.tableIndex]
                            const maxNum  = parseFloat(row.contractAmount) - parseFloat(row.previousTotalAmount)
                            if(parseFloat(value) > maxNum) {
                                callback(new Error('不能超过剩余合同金额'))
                            }else{
                                callback()
                            }

                        },
                        trigger: 'blur'
                    },
                ],
            }
        }
    },
    components: {
        AttachComp,
        ExaHistory,
    },
    created () {
    },
    mounted () {
        this.init()
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'contractList',
            'attach',
            'auditHistory'
        ]
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
        if(this.$route.query.name) {
            setTimeout(()=>{
                this.onChangeTab({
                    name: this.$route.query.name
                })
                this.tabsName = this.$route.query.name
            }, 200)
        }
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    computed: {
        ...mapState({
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            state: state => state.equip.equipData.state, //通用流程状态
        }),
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        },
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        ...mapMutations(['setSelectedInfo']),
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('auditHistory')) {
                    const lastConHeight =
                        document.getElementById('auditHistory').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //设置错误标签
        setError (name) {
            if(!this.errorList.find(x=>x === name)) {
                this.errorList.push(name)
            }
        },
        //清除错误标签
        clearError (name) {
            const index = this.errorList.findIndex(x=>x === name)
            if(index !== -1) {
                this.errorList.splice(index, 1)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item=>{
                let index = this.tabArr.findIndex(x=>x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //获取流程按钮显示状态
        getCurrentUnitInfo () {
            if(this.formData.state !== '-1' && this.formData.state !== '2' && this.formData.state !== '5') {
                getCurrentState(this.auditParams).then(res => {
                    this.auditState = res
                })
            }
        },
        init () {
            showLoading()
            this.getBasic().then(()=>{
                this.getSettlementList(),
                this.getCurrentUnitInfo()  //获取流程按钮显示状态
                hideLoading()
            }).catch(()=>{
                hideLoading()
            })
        },
        //获取基本信息
        getBasic () {
            return new Promise((resolve, reject)=>{
                getBond({ id: this.billid }).then(res=>{
                    this.formData = res
                    resolve()
                }).catch(err=>{
                    reject(err)
                })
            })
        },
        //删除基本信息
        deleteBaseInfo () {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                ()=>{
                    showLoading()
                    deleteBond({ id: this.billid }).then(() => {
                        hideLoading()
                        this.clientPop('suc', '删除成功', this.handleClose)
                    })
                }
            )
        },
        //获取结算列表
        getSettlementList () {
            getBondList({ id: this.billid }).then(res=>{
                this.settlementList = res.code ? [] : res
            })
        },
        //获取审核历史
        getHistoryData () {
            getAuditHistoryLs(this.auditParams).then(res=>{
                this.historyData = res
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.rulesBase.validate(valid => {
                    if (valid) {
                        updateBond(this.formData).then(() => {
                            this.clearError('baseInfo')
                            resolve()
                            this.getBasic()
                        }).catch(err=>{
                            reject(err)
                            this.setError('baseInfo')
                        })
                    } else {
                        this.setError('baseInfo')
                        reject('基本信息错误')
                    }
                })
            })
        },
        //保存清单
        saveSettlementList (isComit = false) {
            return new Promise((resolve, reject)=>{
                let settlementList = []
                settlementList = [...this.settlementList]
                // let valid = false
                if(isComit) {
                    const filterData = settlementList.filter(x=>x.changeType !== -1)
                    if(filterData.length === 0) {
                        this.setError('contractList')
                        reject('必须引入清单')
                        return
                    }
                    else{
                        hideLoading()
                        // valid =  validatorTable('settlementRef', this.settleRules, filterData, this, 'tableIndex')
                        this.errorContractMsg = []
                        filterData.forEach((item, index)=>{
                            // const maxNum  = parseFloat(item.contractAmount) - parseFloat(item.previousTotalAmount)
                            // if(parseFloat(item.settlementAmount) > maxNum) {
                            //     this.setErrorContractMsg(`第${index + 1}行本期结算金额不能超过剩余合同金额`)
                            // }
                            if(parseFloat(item.currentTotalAmount) > parseFloat(item.contractAmount)) {
                                this.setErrorContractMsg(`第${index + 1}行截止本期末累计结算金额不能超合同金额`)
                            }
                        })
                        if(this.errorContractMsg.length > 0) {
                            this.setError('contractList')
                            reject('结算清单错误')
                            return
                        }else{
                            this.clearError('contractList')
                        }
                    }

                }else{
                    if(settlementList.length === 0) {
                        resolve()
                        return
                    }
                }
                const filterData = settlementList.filter(x=>x.changeType !== 0)
                console.log('filterData', filterData)
                const newListAll =  filterData.map(x=>{
                    const obj = {
                        'billId': '',
                        'changeType': 0,
                        'contractAmount': 0,
                        'contractProportion': 0,
                        'currentTotalAmount': 0,
                        'currentTotalProportion': 0,
                        'dtlId': '',
                        'itemId': '',
                        'itemName': '',
                        'itemNo': '',
                        'marginType': 0,
                        'previousTotalAmount': 0,
                        'previousTotalProportion': 0,
                        'settlementAmount': 0,
                        'settlementProportion': 0
                    }
                    for(let key in obj) {
                        obj[key] = x[key]
                    }
                    return obj
                })
                console.log('newListAll', newListAll)
                if(newListAll.length === 0) {
                    resolve()
                    return false
                }
                updateBondList(newListAll).then(()=>{
                    this.clearError('contractList')
                    resolve()
                    this.getSettlementList()
                }).catch(err=>{
                    this.setError('contractList')
                    reject(err)
                })
            })

        },
        setErrorBondMsg (msg) {
            let index = this.errorBondMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorBondMsg.push(msg)
            }
        },
        //先保存结算清单 再保存基本信息
        saveMianList (isComit = false) {
            return new Promise((resolve, reject)=>{
                this.saveSettlementList(isComit).then(()=>{
                    this.updateBaseInfo().then(()=>{
                        resolve()
                    }).catch(err=>{
                        reject(err)
                    })
                }).catch(err=>{
                    reject(err)
                })

            })
        },
        //保存全部数据
        saveAll () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.saveMianList(),
            ])
                .then(() => {
                    this.$store.commit('contract/setMaterialList', [])
                    hideLoading()
                    this.clientPop('suc', '保存成功')
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    this.clientPop('err', '保存失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        //保存并提交
        submitCommit () {
            showLoading()
            this.errorList = []
            Promise.all([
                this.saveMianList(true),
            ])
                .then(() => {
                    this.$store.commit('contract/setMaterialList', [])
                    flowCommit(this.auditParams).then(()=>{
                        hideLoading()
                        this.clientPop('suc', '提交成功', this.handleClose)
                    })
                })
                .catch(err => {
                    console.log('errMsg：', err)
                    this.clientPop('err', '提交失败', ()=>{
                        this.scorllError()
                    })
                })
                .finally(() => {
                    hideLoading()
                })
        },
        //保存
        submit () {
            this.saveAll()
        },
        //取消
        handleClose () {
            hideLoading()
            this.$router.replace('/baozhengjinList')
        },
        tableRowClassName ({ row }) {
            if(row.changeType === -1) {
                if(row.hasChildren) {
                    return `class-${row.billId} row-hide`
                }else{
                    return `class-${row.billId}  row-hide hide-icon`
                }
            }else{
                if(row.hasChildren) {
                    return `class-${row.billId} row-show`
                }else{
                    return `class-${row.billId}  row-show hide-icon`
                }
            }
        },
        //选择合同
        selectContract () {
            const ids = this.formData.contractId ? [this.formData.contractId] : []
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/subcontract/thirdParty/getReturnBondSettlement', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择合同', // 标题
            }).then(val => {
                this.clearList()
                this.formData.contractName = val[0].contractName
                this.formData.contractId = val[0].contractId
                this.formData.currency = val[0].currencyName
                this.formData.currencyId = val[0].currencyId
                this.formData.baseCurName = val[0].baseCurName
                this.formData.baseCurId = val[0].baseCurId
                this.formData.baseCurRate = val[0].baseCurId === val[0].currencyId ? 1 : val[0].baseCurRate
                this.showBaseCurName = val[0].baseCurId === val[0].currencyId ? false : true
                this.formData.rmbRate = val[0].rmbRate
                this.formData.outsourcerName = val[0].secondPartyName
                this.formData.outsourcerId = val[0].secondPartyId
                listPreviousTotalReturnDepositInfo({
                    contractId: this.formData.contractId,
                    orgId: this.formData.orgId,
                }).then(res=>{
                    val[0].bonds.forEach(item=>{
                        const depositInfo1 = res.find(x=>x.itemId === item.billId && x.marginType === 1) //扣类
                        const depositInfo2 = res.find(x=>x.itemId === item.billId && x.marginType === 2) //返类
                        const obj1 = { //扣类
                            'billId': this.billid,
                            'changeType': 1,
                            'contractAmount': item.deductionAmount,
                            'contractProportion': item.deductionRatio,
                            'currentTotalAmount': 0,
                            'currentTotalProportion': 0,
                            'dtlId': '',
                            'itemId': item.billId,
                            'itemName': item.name,
                            'itemNo': '扣',
                            'marginType': 1,
                            'previousTotalAmount': depositInfo1 ? depositInfo1.previousTotalAmount : 0,
                            'previousTotalProportion': depositInfo1 ? depositInfo1.previousTotalProportion : 0,
                            'settlementAmount': 0,
                            'settlementProportion': 0
                        }

                        this.settlementList.push(obj1)
                        const obj2 = { //返类
                            'billId': this.billid,
                            'changeType': 1,
                            'contractAmount': item.deductionAmount,
                            'contractProportion': item.deductionRatio,
                            'currentTotalAmount': 0,
                            'currentTotalProportion': 0,
                            'dtlId': '',
                            'itemId': item.billId,
                            'itemName': item.name,
                            'itemNo': '返',
                            'marginType': 2,
                            'previousTotalAmount': depositInfo2 ? depositInfo2.previousTotalAmount : 0,
                            'previousTotalProportion': depositInfo2 ? depositInfo2.previousTotalProportion : 0,
                            'settlementAmount': 0,
                            'settlementProportion': 0
                        }
                        this.settlementList.push(obj2)
                    })
                    this.summaryAmount()
                })

            })
        },
        showContract () {
            if(!this.formData.contractId) return
            openAppClient(`/contractDefinitionShow?billid=${this.formData.contractId}&isview=true`, '查看分包合同')
        },
        //清空清单
        clearList () {
            for(let i = 0;i < this.settlementList.length;i++) {
                if( this.settlementList[i].changeType === 1 ) {
                    this.settlementList.splice(i, 1)
                    i--
                }else{
                    this.settlementList[i].changeType = -1
                }
            }
        },
        setErrorContractMsg (msg) {
            let index = this.errorContractMsg.findIndex(x=>x === msg)
            if(index === -1) {
                this.errorContractMsg.push(msg)
            }
        },
        //修改金额
        changeAmount (row, index) {
            this.tableIndex = index
            row.changeType = row.changeType !== -1 && row.changeType !== 1 ? 2 : 1
            row.settlementProportion =  (parseInt(row.settlementAmount ? row.settlementAmount : 0) * 100 / parseFloat(row.contractAmount)).toFixed(2)
            row.currentTotalAmount = parseFloat(row.settlementAmount ? row.settlementAmount : 0)  +  parseFloat(row.previousTotalAmount)
            row.currentTotalProportion = (parseInt(row.currentTotalAmount ? row.currentTotalAmount : 0) * 100 / parseFloat(row.contractAmount)).toFixed(2)
            this.summaryAmount()
        },
        //汇总金额
        summaryAmount () {
            this.formData.amount = this.settlementList.reduce(((prev, item)=>{
                return prev + (item.changeType !== -1 ? parseInt(item.settlementAmount)  : 0)
            }), 0)
        },
        isNumInput (event) {
            isNumInput(event)
        },
        exas (arg) {
            if (arg === 'audit') {
                showLoading()
                this.errorList = []
                hideLoading()
                this.setAuditParams(this.auditParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/exaDialog', '填写审核意见', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    showLoading()
                    flowAudit(auditParams).then(() => {
                        hideLoading()
                        this.clientPop('suc', '审核成功', this.handleClose)
                    }).catch(()=>{
                        hideLoading()
                    })
                })
            } else if (arg === 'undoAudit') {
                console.log(12345)
                showLoading()
                flowUndoAudit(this.auditParams).then(() => {
                    hideLoading()
                    this.clientPop('suc', '撤回成功', this.handleClose)
                }).catch(() => {
                    hideLoading()
                })
            } else if (arg === 'submitCommit') {
                this.submitCommit()  //保存并提交
            } else if (arg === 'submit') {
                this.saveAll()   //保存
            } else if (arg === 'nullify') {
                this.setAuditParams(this.nullifyParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/nullifyDialog', '单据作废原因', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    showLoading()
                    flownullify(auditParams).then(() => {
                        hideLoading()
                        this.clientPop('suc', '作废成功', this.handleClose)
                    }).catch(() => {
                        hideLoading()
                        this.clientPop('err', '作废失败', this.handleClose)
                    })
                })
            } else if (arg === 'deleteData') {
                this.deleteBaseInfo()
            }
        },
    }
}
</script>

<style lang="scss" scoped>
    ::v-deep .el-table__row{
        .cell{
            display: flex;
            align-items: center;
        }
        td:nth-child(3),td:nth-child(4),td:nth-child(5),td:nth-child(6),td:nth-child(7),td:nth-child(8),td:nth-child(9){
            .cell{
                justify-content: flex-end;
            }
        }
        td:nth-child(1),td:nth-child(2){
            .cell{
                justify-content: flex-start;
            }
        }
    }
    ::v-deep .has-gutter{
        .cell{
            display: flex;
            align-items: center;
        }
        th:nth-child(3),th:nth-child(4),th:nth-child(5),th:nth-child(6),th:nth-child(7),th:nth-child(8),th:nth-child(9){
            .cell{
                text-align: right;
            }
        }
        th:nth-child(1),th:nth-child(2){
            .cell{
                text-align: left;
            }
        }
    }
</style>
